YUI.add('wfdata', function (Y) {
	
	var history = new Y.HistoryHash();
	
	var undoLink = Y.one('#undo-link'),
		redoLink = Y.one('#redo-link');
	undoLink.setStyle('color','gray');
	redoLink.setStyle('color','gray');
	
	function getItemState(c,prev){
		var cc = Y.clone(c,true);
		delete cc.action;
		delete cc.mid;
		delete cc.touchedpath;
		delete cc.uid;
		var ccc = {};
		Y.each(Y.Object.keys(cc),function(k){
			if(prev){
				ccc[k] = cc[k].prevVal;
			}else{
				ccc[k] = cc[k].newVal;
			}
		});
		return ccc;
	}
	
	function restoreDeletedItem(c){
		var cc = Y.clone(c,true);
		Y.projectListList[cc.dp].create(cc);
	}
	Y.namespace('AppStatus');
	Y.changeHistory = {
			data : [],
			syncData : [],
			undoPoint : -1,
			add : function(m){
				if(Y.AppStatus.redoStart || Y.AppStatus.undoStart){
					;
				}else{
					if(this.data.length != this.undoPoint + 1){
						this.data = this.data.slice(0,this.undoPoint + 1);
					}
					this.data.push(m);
//					Y.log(Y.dump(m));
					undoLink.setStyle('color','#0066CC');
					this.undoPoint = this.data.length - 1;

				}
				if(!Y.processingCollide){
					this.syncData.push(m);
					Y.showSyncMsg(Y.translator.notSyncYet());
				}
				
				Y.log('undoPoint:' +this.undoPoint);
				Y.log('change length:' + this.data.length);
				
//				if(this.undoPoint < 0){
//					undoLink.setStyle('color','gray');
//				}else{
//					undoLink.setStyle('color','#0066CC');
//				}
//				
//				if(this.undoPoint >= this.data.length - 1){
//					redoLink.setStyle('color','gray');
//				}else{
//					redoLink.setStyle('color','#0066CC');
//				}
			},
			undo : function(){
				if(this.undoPoint < 0){
					if(this.data.length > 0){
						redoLink.setStyle('color','#0066CC');
					}
					return;
				}
				var undodata = this.data[this.undoPoint];
				//可能是删除，可能是添加，可能是修改
				if(undodata.action == 'delete'){
					restoreDeletedItem(undodata);
				}else if(undodata.action == 'add'){
					var model = Y.Wfutils.getModelById(undodata.mid);
					if(model){
						model.destroy({'delete':true});
					}
				}else{
					var c = getItemState(undodata,true); 
					Y.log(Y.dump(c));
					Y.log(Y.dump(undodata));
					var model = Y.Wfutils.getModelById(undodata.mid);
					//如果model存在的话
					Y.log(model);
					if(model){
						model.setAttrs(c).save();
							if(c.dp){
								Y.projectListList[undodata.dp.prevVal].add(model);
								Y.projectListList[undodata.dp.newVal].remove(model);
							}else if(c.position){
								Y.projectListList[model.get('dp')].remove(model);
								Y.projectListList[model.get('dp')].add(model);
							}
					}
				}
				this.undoPoint--;
				redoLink.setStyle('color','#0066CC');
				if(this.undoPoint < 0){
					undoLink.setStyle('color','gray');
				}
			},
			redo : function(){
				if(this.undoPoint >= this.data.length - 1){
					redoLink.setStyle('color','gray');
					return;
				}
				this.undoPoint++;
				var redodata = this.data[this.undoPoint];
				Y.log(redodata);
				if(redodata.action == 'delete'){//删除的还是删除
					var model = Y.Wfutils.getModelById(redodata.mid);
					if(model){
						model.destroy({'delete':true});
					}
				}else if(redodata.action == 'add'){
					restoreDeletedItem(redodata);//添加的还是添加
				}else{
					var c = getItemState(redodata);
					Y.log(c);
					var model = Y.Wfutils.getModelById(redodata.mid);
					//如果model存在的话
					if(model){
						model.setAttrs(c).save();
						if(c.dp){
							Y.projectListList[redodata.dp.newVal].add(model);
							Y.projectListList[redodata.dp.prevVal].remove(model);
						}else if(c.position){
							Y.projectListList[model.get('dp')].remove(model);
							Y.projectListList[model.get('dp')].add(model);
						}

					}
				}
				undoLink.setStyle('color','#0066CC');
			},
			getSyncData:function(){
				var d = this.syncData.slice(0);
				this.syncData = [];
				return mergeChange(d);
			}
	};
	
	function mergeChange(ca){
		var ra = [];
		_mergeChange(ca, ra);
		return ra;
	}
	
	function _mergeChange(ca,ra){
		if(ca && ca.length > 0){
			var a = ca.shift();
			var newca = [];
			Y.each(ca,function(item){
				if(a.action == item.action && a.mid == item.mid){
					a = Y.merge(a,item);
				}else{
					newca.push(item);
				}
			});
			ra.push(a);
			if(newca.length > 0){
				_mergeChange(newca, ra);
			}
		}
	}
	
	var history = new Y.HistoryHash();
	
	if(history.get('item')){
		Y.rootEntry = history.get('item');
	}else{
		Y.rootEntry = 'nop';
	}
	
	var tH = {
            success: function(id, o, args) {
    			var r = Y.JSON.parse(o.responseText);
    			var res = r.response;
    			if(res.status === 0){
        			Y.hideMsg();
    				createMemoryData(res.data);
    				Y.lastTransId = res.lastTransId;
    			}else if(res.status == -110){
    				Y.showWarn("操作被拒绝！请确认是否对此条目有访问权限！");
    			}else{
    				Y.showWarn("登录状态监测出错，请尝试刷新浏览器！");
    			}
            },
            failure: function(id, o, args) {
            			Y.showWarn("下载数据出错，请刷新浏览器再次尝试！");
                     }
        };
        /* configuration object for transactions */
    
    function getQueryObject(uid){
    	return {
    		method:'GET',
            on: {
                success: tH.success,
                failure: tH.failure
            },
            data:{'_modelName':'com.m3958.firstgwt.server.model.WorkFlowProject',
				'_queryName':'findWorkProjectByUserId',
				'_operationType':'fetch',
				'_subOperationType':'NAMED_QUERY'},
            
//            {'_modelName':'com.m3958.firstgwt.server.model.WorkFlowProject',
//				'_sortBy':'position',
//				'_operationType':'fetch',
//				'_isMaster':true,
//				'_relationModelId':uid,
//				'_relationModelName':'com.m3958.firstgwt.server.model.user',
//				'_relationPropertyName':'creator',
//				'_subOperationType':'FETCH_ONE_TO_MANY'},
            context: tH,
            arguments: {}
    	};
    }
    
    function getSharedQueryObject(itemId){
    	return {
    		method:'GET',
            on: {
                success: tH.success,
                failure: tH.failure
            },
            data:
            {'_modelName':'com.m3958.firstgwt.server.model.WorkFlowProject',
				'_queryName':'findWorkProjectsByUUID',
				'_operationType':'fetch',
				'_subOperationType':'NAMED_QUERY',
				'_itemId':itemId
            	},
//            {'_modelName':'com.m3958.firstgwt.server.model.WorkFlowProject',
//				'_sortBy':'position',
//				'_operationType':'fetch',
//				'path':itemId,
//				'uuid':itemId,
//				'_textMatchStyle':'substring',
//				'_wheremode':'or'
//            	},
            	
            context: tH,
            arguments: {}
    	};
    }
    
    function createMemoryData(initData){
//	    var initData = Y.JSON.parse((Y.localStorage && Y.localStorage.getItem(Y.localKey)) || '[]');
    	if(initData && initData.length > 0){
    		var r = initData[0];
    		Y.ownerUserId = r.uid;
    	}else{
    		if(Y.loginUser){
    			Y.ownerUserId = Y.loginUser.id;
    		}else{
    			Y.ownerUserId = -1;
    		}
    	}
		Y.totalData = new Y.Recordset({records: initData});
		Y.totalData.plug(Y.Plugin.RecordsetFilter);
		Y.totalData.plug(Y.Plugin.RecordsetIndexer);
		Y.totalDataHash = Y.totalData.indexer.createTable('uuid');
		if(Y.sharedMode){
			var sr = Y.totalDataHash[Y.rootEntry];
			if(sr){
				if('public-editable' == sr.getValue('shareType')){
					;
				}else{
					Y.readOnly = true;
				}
			}
		}
		
		var item = history.get('item');
		Y.entryItem(item);
		var q = history.get('q');
		if(q){
			Y.filterProject(q);
		}
    }
    
    Y.resetLocalData = function(rs){
    	Y.localData = new Y.Recordset({records:rs});
		Y.localData.plug(Y.Plugin.RecordsetFilter);
		Y.localData.plug(Y.Plugin.RecordsetIndexer);
		Y.localData.plug(Y.Plugin.RecordsetSort);
		Y.localData.sort.sort('position', false);
		Y.localDataHash = Y.localData.indexer.createTable('uuid');
		Y.fire('dataReady');
    }
	
	Y.on('loginStatus',function(e){
		if(e.login){
			Y.localKey = e.user.id + "";
			Y.showMsg('正在从服务器下载数据，请稍侯......');
			if(Y.sharedMode){
				Y.io('/smartcfud', getSharedQueryObject(history.get('item')));
			}else{
				Y.io('/smartcfud', getQueryObject(e.user.id));
			}
		}else{
			if(Y.sharedMode){
				Y.io('/smartcfud', getSharedQueryObject(history.get('item')));
			}else{
				Y.localKey = 'nobody';
				createMemoryData([]);
			}
		}
	});

},'0.0.1',{requires:['history','transition','dump']});